package com.quanyan.operative.web.filter;

import com.alibaba.fastjson.JSON;
import com.quanyan.api.APIResponse;
import com.quanyan.api.enums.ApiResponseEnum;
import com.quanyan.common.constants.Constants;
import com.quanyan.common.user.AppUserCacheInfo;
import com.quanyan.common.utils.HttpServletRequestWrapper;
import com.quanyan.common.utils.MD5Utils;
import com.quanyan.redisCluster.config.RedisTemplate;
import com.quanyan.redisCluster.utils.RedisKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;


/**
 * @Author huadongyang
 * @Since 2016-11-28
 */
@Component
public class CommonFilter implements Filter {

    private final static Logger logger = LoggerFactory.getLogger(CommonFilter.class);

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    private void ajaxError(ApiResponseEnum apiResponseEnum, ServletResponse response)
            throws IOException {
        response.getWriter().write(JSON.toJSON(APIResponse.returnFail(apiResponseEnum)).toString());
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        Long startTime = System.currentTimeMillis();
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        String uri = request.getRequestURI().replaceAll("//", "/");
        String sign = request.getHeader("sign");
        String userCookiesName = request.getHeader("userCookiesName");
        logger.info("uri:" + uri + ";sign:" + sign + ";userCookiesName:" + userCookiesName);
        ServletRequest requestWrapper = new HttpServletRequestWrapper(request);
        String reqData = getBodyString(requestWrapper.getReader(), uri);
        logger.info("CommonFilter读取body中的参数: " + reqData);

        if (uri.startsWith("/api/operative/place/getPlaceList")
                || uri.startsWith("/api/operative/place/getSubjectAndActivity")
                || uri.startsWith("/api/operative/blessing")
                || uri.startsWith("/api/operative/doubleEggFestival/helpFriendHitEgg")
                || uri.startsWith("/api/operative/doubleEggFestival/getUserHitEggList")
                || uri.startsWith("/api/operative/doubleEggFestival/getUserEggshellNum")
                || uri.startsWith("/api/operative/opact/opActivities")
                || uri.startsWith("/api/operative/opact/opActivityInfo")
                || uri.startsWith("/api/operative/opact/getDynamicLikeList")
                || uri.startsWith("/api/operative/opact/getCommentItem")
                || uri.startsWith("/api/operative/opact/getCommentList")
                || uri.startsWith("/api/operative/snatch/getSnatchGoodsList")
                || uri.startsWith("/api/operative/snatch/getWinningInfoList")
                || uri.startsWith("/api/operative/snatch/getParticipants")
//                || uri.startsWith("/api/operative/opact/getDynamicItem")
//                || uri.startsWith("/api/operative/opact/getDynamicList")
                ) {
        } else {
            RedisKey redisKey = new RedisKey(userCookiesName, "");
            AppUserCacheInfo appUserCacheInfo = (AppUserCacheInfo) redisTemplate.getObjectFromC(redisKey, AppUserCacheInfo.class);

            String md5Sign = MD5Utils.MD5Encode(reqData + Constants.SECRET_KEY);
            logger.info("md5ign:" + md5Sign);
            if (sign == null || !sign.equals(md5Sign)) {
                ajaxError(ApiResponseEnum.ILLEGAL_PROTOCOL, response);
                return;
            }

            if (appUserCacheInfo == null) {
                ajaxError(ApiResponseEnum.COOKIES_IS_NULL, response);
                return;
            } else {
                Integer uid = appUserCacheInfo.getUser_id();
                String dsn = appUserCacheInfo.getDsn();
                if (uid != null && uid > 0) {
                    request.setAttribute("uid", uid);
                    request.setAttribute("dsn", dsn);
                }else if(uid != null && uid.equals(0) &&
                        uri.startsWith("/api/operative/snatch/enterSpec")){
                    request.setAttribute("uid", uid);
                    request.setAttribute("dsn", dsn);
                }
            }

        }

        chain.doFilter(requestWrapper, response);

        logger.info("接口【" + uri + "】执行时间为：" + (System.currentTimeMillis() - startTime) + "毫秒");
    }

    public static String getBodyString(BufferedReader br, String reqUrl) {
        String inputLine;
        StringBuilder sb = new StringBuilder();
        try {
            while ((inputLine = br.readLine()) != null) {
                sb.append(inputLine);
            }
            br.close();
        } catch (IOException e) {
            logger.warn("requestUrl: " + reqUrl + ", Request error: "
                    + e.getMessage() + "Request URI: ");
        }
        return sb.toString();
    }

    @Override
    public void destroy() {

    }
}
